package com.fingard.dsp.bank.directbank.cwgs01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;

/**
 * Created by F on 2019/4/25.
 */
public class CWGS01Base extends DirectBase {
    private static TransIDHelper idHelper = new TransIDHelper(1, 999);
    protected static String getQryTransID(String startStr) {
        String tmpDateNow=Format.DateTime14Format.format(new Date());
        return tmpDateNow.substring(0,8)+startStr+tmpDateNow.substring(8)+idHelper.getNextIDStr();
    }
    protected String getCharset(){
        return getBankConfig().getCharset("GBK");
    }


    protected void wirteCommenHeader(XmlTextWriter xmlTextWriter, CWGS01Header header) {
        xmlTextWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        xmlTextWriter.writeStartElement("XERP");
        xmlTextWriter.writeStartElement("HEAD");
        xmlTextWriter.writeElementString("BATCH_NO", header.batchNo);
        xmlTextWriter.writeElementString("CHANNEL_ID", "YM");
        xmlTextWriter.writeElementString("BIZCODE", header.bizCode);
        xmlTextWriter.writeEndElement();
    }
//    protected String[] sendToBank(String p_reqStr) throws Exception{
//        String[] retStr = new String[]{"",""};
//
//        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverURL);
//        WriteBankLogStep2(p_reqStr);
//        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
//        tmpWebRequest.setConnectTimeout(60000);
//        tmpWebRequest.setRequestProperty("Content-Type", "application/xml");
//        tmpWebRequest.setRequestProperty("connection", "Close");
//        String charsetName = getCharset();
//        byte[] tmpToWriteBytes = p_reqStr.getBytes(charsetName);
//        retStr = tmpWebRequest.upload(tmpToWriteBytes, charsetName);
//        WriteBankLogStep3(retStr[1]);
//        return retStr;
//    }

    protected String[] sendToBank(String p_reqStr)throws Exception{
        String endpoint = bankFront.serverURL;
        WriteBankLogLn("请求银行的地址：" + endpoint);
//        // 直接引用远程的wsdl文件
        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setTargetEndpointAddress(endpoint);
        call.setOperationName("send");// WSDL里面描述的接口名称
        call.addParameter("sendRequest",
                org.apache.axis.encoding.XMLType.XSD_STRING,
                javax.xml.rpc.ParameterMode.IN);// 接口的参数
        call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
        WriteBankLogLn("2.发送银行的报文：" + p_reqStr);
        String result = (String) call.invoke(new Object[] { p_reqStr });
        WriteBankLogLn("3.银行返回的报文：" + result);
        return new String[]{"",result};

}

    public static void main(String[] args) throws Exception {
        for(int i=0;i<100;i++){
            System.out.println(getQryTransID("7506"));
        }
        /*String endpoint = "http://119.97.248.174:7240/XERP/service/TxService";
        String p_reqStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<XERP>\n" +
                "  <HEAD>\n" +
                "    <BATCH_NO>19449003</BATCH_NO>\n" +
                "    <CHANNEL_ID>YM</CHANNEL_ID>\n" +
                "    <BIZCODE>2001</BIZCODE>\n" +
                "  </HEAD>\n" +
                "  <BODY>\n" +
                "    <USERNAME>111</USERNAME>\n" +
                "    <PWD>1</PWD>\n" +
                "  </BODY>\n" +
                "</XERP>";
//        // 直接引用远程的wsdl文件
        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setTargetEndpointAddress(endpoint);
        call.setOperationName("send");// WSDL里面描述的接口名称
        call.addParameter("sendRequest",
                org.apache.axis.encoding.XMLType.XSD_STRING,
                javax.xml.rpc.ParameterMode.IN);// 接口的参数
        call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
//        String temp = "测试人员";
        String result = (String) call.invoke(new Object[] { p_reqStr });
//        // 给方法传递参数，并且调用方法
//        System.out.println("result is " + result);
        System.out.println("2.发送银行的报文：" + p_reqStr);

//        TxService txService = new TxService();
//        TxServicePortType txServicePortType =txService.getTxServiceHttpPort();
//        String msg = p_reqStr;
//        String result = txServicePortType.send(msg);
        System.out.println("3.银行返回的报文：" + result);*/
    }

    //登入
    protected String login(String startStr) throws Exception{

            XmlTextWriter xmlWriter =  new XmlTextWriter();
            CWGS01Header header = new CWGS01Header();
            header.batchNo = getQryTransID(startStr);
            header.bizCode ="1001";
            wirteCommenHeader(xmlWriter,header);
            xmlWriter.writeStartElement("BODY");
            xmlWriter.writeElementString("USERNAME",bankFront.loginName );
            xmlWriter.writeElementString("PWD", bankFront.loginPasswd);
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if(bankResult[0].length() ==0){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1],tmpSbMsg);
                    String retCode =tmpBkReader.getFirstText("/XERP/BODY/RET_CODE");
                    String retMsg = tmpBkReader.getFirstText("/XERP/BODY/RET_MSG");
                    if("0".equals(retCode)) {
                        return  tmpBkReader.getFirstText("/XERP/BODY/VALIDATE_CODE");
                    } else{
                       throw new Exception( retCode+":" +retMsg);

                    }
            }else{
                throw new Exception(bankResult[1]);
            }

    }

    //注销
    protected void logout(String validcode,String startStr){
        try {
            XmlTextWriter xmlWriter =  new XmlTextWriter();
            CWGS01Header header = new CWGS01Header();
            header.batchNo = getQryTransID(startStr);
            header.bizCode ="1002";
            wirteCommenHeader(xmlWriter,header);
            xmlWriter.writeStartElement("BODY");
            xmlWriter.writeElementString("USERNAME",bankFront.loginName);
            xmlWriter.writeElementString("VALIDATE_CODE", validcode);
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if(bankResult[0].length() ==0){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1],tmpSbMsg);
//                    String retCode =tmpBkReader.getFirstText("/XERP/BODY/RET_CODE");
                    String retMsg = tmpBkReader.getFirstText("/XERP/BODY/RET_MSG");
                    WriteBankLogLn( retMsg);
            }else{
                WriteBankLogLn( bankResult[1]);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            WriteBankLogLn( ex);
        }
    }




}
